<template>
  <div class="workflow-loader">
    <!-- JSON 文件上传 -->
    <el-upload
      class="json-uploader"
      accept=".json"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleFileChange"
      drag
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        将 ComfyUI 工作流文件拖到此处，或<em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          支持导入 ComfyUI 导出的 JSON 工作流文件
        </div>
      </template>
    </el-upload>

    <!-- 工作流预览 -->
    <div v-if="workflow" class="workflow-preview">
      <el-alert
        v-if="validationErrors.length"
        type="warning"
        :closable="false"
        show-icon
      >
        <template #title>工作流验证警告</template>
        <template #default>
          <ul class="validation-errors">
            <li v-for="(error, index) in validationErrors" :key="index">
              {{ error }}
            </li>
          </ul>
        </template>
      </el-alert>

      <!-- 基本信息 -->
      <el-card class="mb-4">
        <template #header>
          <div class="card-header">
            <span>工作流信息</span>
            <el-button-group>
              <el-button 
                type="primary" 
                :disabled="!!validationErrors.length"
                @click="importWorkflow"
              >
                导入工作流
              </el-button>
              <el-button @click="resetWorkflow">重置</el-button>
            </el-button-group>
          </div>
        </template>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="节点数量">
            {{ workflow.nodes?.length || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="连接数量">
            {{ workflow.edges?.length || 0 }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 节点分析 -->
      <el-card class="mb-4">
        <template #header>
          <div class="card-header">
            <span>节点分析</span>
          </div>
        </template>

        <el-table :data="nodeAnalysis" style="width: 100%">
          <el-table-column prop="type" label="节点类型" />
          <el-table-column prop="count" label="数量" width="120" />
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button size="small" @click="showNodeDetails(row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 工作流图 -->
      <el-card>
        <template #header>
          <div class="card-header">
            <span>工作流预览</span>
          </div>
        </template>

        <div class="workflow-graph" id="workflow-preview">
          <workflow-graph
            v-if="workflow"
            v-model:nodes="workflow.nodes"
            v-model:edges="workflow.edges"
            :readonly="true"
          />
        </div>
      </el-card>
    </div>

    <!-- 节点详情对话框 -->
    <el-dialog
      v-model="nodeDialog.visible"
      :title="nodeDialog.title"
      width="800px"
    >
      <el-table :data="nodeDialog.nodes" style="width: 100%">
        <el-table-column prop="id" label="节点ID" width="180" />
        <el-table-column prop="type" label="类型" width="150" />
        <el-table-column label="输入参数">
          <template #default="{ row }">
            <el-descriptions :column="1" border>
              <el-descriptions-item
                v-for="(value, key) in row.inputs"
                :key="key"
                :label="key"
              >
                {{ formatParamValue(value) }}
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'
import WorkflowGraph from './WorkflowGraph.vue'
import { validateWorkflow } from '@/utils/workflow'
import { exportWorkflowToJson } from '@/utils/export'
import type { WorkflowNode, WorkflowEdge } from '@/types/workflow'

interface WorkflowData {
  nodes: WorkflowNode[]
  edges: WorkflowEdge[]
  [key: string]: any
}

const emit = defineEmits<{
  (e: 'import', workflow: WorkflowData): void
}>()

// 工作流数据
const workflow = ref<WorkflowData | null>(null)
const validationErrors = ref<string[]>([])

// 节点分析
const nodeAnalysis = computed(() => {
  if (!workflow.value?.nodes) return []

  const analysis = new Map<string, number>()
  workflow.value.nodes.forEach(node => {
    const count = analysis.get(node.type) || 0
    analysis.set(node.type, count + 1)
  })

  return Array.from(analysis.entries()).map(([type, count]) => ({
    type,
    count,
    nodes: workflow.value?.nodes.filter(node => node.type === type)
  }))
})

// 节点详情对话框
const nodeDialog = ref({
  visible: false,
  title: '',
  nodes: [] as WorkflowNode[]
})

// 处理文件上传
const handleFileChange = (file: UploadFile) => {
  if (!file.raw) {
    ElMessage.error('文件读取失败')
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const json = JSON.parse(e.target?.result as string)
      analyzeWorkflow(json)
    } catch (error) {
      console.error('Failed to parse JSON:', error)
      ElMessage.error('无效的工作流文件')
    }
  }
  reader.readAsText(file.raw)
}

// 分析工作流
const analyzeWorkflow = (data: any) => {
  try {
    // 验证基本结构
    if (!data || typeof data !== 'object') {
      throw new Error('无效的工作流文件格式')
    }

    // 验证节点数据
    if (!Array.isArray(data.nodes)) {
      throw new Error('无效的节点数据')
    }

    // 验证连接数据
    if (!Array.isArray(data.edges)) {
      throw new Error('无效的连接数据')
    }

    // 处理节点数据
    const nodes = data.nodes.map((node: any) => ({
      id: node.id || `node_${Date.now()}_${Math.random()}`,
      type: node.type || 'unknown',
      inputs: node.inputs || {},
      outputs: node.outputs || {},
      position: node.position || { x: 0, y: 0 },
      ...node
    }))

    // 处理连接数据
    const edges = data.edges.map((edge: any) => ({
      id: edge.id || `edge_${edge.source}_${edge.target}`,
      source: edge.source,
      target: edge.target,
      ...edge
    }))

    // 验证工作流
    const errors = validateWorkflow(nodes, edges)
    validationErrors.value = errors

    workflow.value = {
      ...data,
      nodes,
      edges
    }

    ElMessage.success('工作流加载成功')
  } catch (error: any) {
    console.error('Failed to analyze workflow:', error)
    ElMessage.error(error.message || '工作流分析失败')
  }
}

// 导入工作流
const importWorkflow = () => {
  if (!workflow.value) return
  if (validationErrors.value.length) {
    ElMessage.warning('请先修复工作流中的错误')
    return
  }

  emit('import', workflow.value)
  ElMessage.success('工作流导入成功')
}

// 重置工作流
const resetWorkflow = () => {
  workflow.value = null
  validationErrors.value = []
}

// 显示节点详情
const showNodeDetails = (row: { type: string; nodes: WorkflowNode[] }) => {
  nodeDialog.value = {
    visible: true,
    title: `${row.type} 节点详情`,
    nodes: row.nodes
  }
}

// 格式化参数值
const formatParamValue = (value: any): string => {
  if (value === null || value === undefined) return '-'
  if (typeof value === 'object') return JSON.stringify(value)
  return String(value)
}

// 导出组件方法
defineExpose({
  getWorkflowData: () => workflow.value,
  exportToJson: () => {
    if (workflow.value) {
      exportWorkflowToJson(workflow.value.nodes, workflow.value.edges)
    }
  }
})
</script>

<style scoped lang="scss">
.workflow-loader {
  .json-uploader {
    margin-bottom: 24px;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration);

    &:hover {
      border-color: var(--el-color-primary);
    }

    .el-upload {
      display: block;
    }

    .el-icon--upload {
      font-size: 67px;
      color: var(--el-text-color-secondary);
      margin: 40px 0 16px;
      line-height: 50px;
    }

    .el-upload__text {
      color: var(--el-text-color-regular);
      font-size: 14px;
      text-align: center;
      margin: 0 0 16px;

      em {
        color: var(--el-color-primary);
        font-style: normal;
      }
    }
  }

  .workflow-preview {
    .validation-errors {
      margin: 0;
      padding-left: 20px;
      
      li {
        line-height: 1.8;
      }
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .workflow-graph {
      height: 600px;
    }
  }
}
</style>